package com.sd.projectinterface;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

@SuppressLint({ "ParserError", "ParserError", "ParserError" })
public class GameStats extends Activity{
	
	TextView title, yourScore, theirScore;
	Button back;
	int id, gameId, competitorId;
	public static final String KEY_121 = "http://10.0.2.2/mathRomp/getGameScores.php";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.game_stats);
		MyApplication myApp = (MyApplication) getApplicationContext();
        id = myApp.getId();
		Bundle incoming = this.getIntent().getExtras();
        //id = incoming.getInt("userId");
        gameId = incoming.getInt("gameId");
        competitorId = incoming.getInt("competitorId");
        
		title = (TextView) findViewById(R.id.game_with);
		yourScore = (TextView) findViewById(R.id.your_points);
		theirScore = (TextView) findViewById(R.id.their_points);
		back = (Button) findViewById(R.id.back);
		
		back.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent i = new Intent(GameStats.this, MyGames.class);
				i.putExtra("j", id);
				startActivity(i);
			}
		});
		
		JSONArray jArray = getScores();
		
		for(int i=0; i<jArray.length(); i++){
			JSONObject json_data;
			try {
				json_data = jArray.getJSONObject(i);
				if(json_data.getInt("userId") == id){
					yourScore.setText(yourScore.getText()+" "+json_data.getInt("userScore"));
				}else if(json_data.getInt("userId") == competitorId){
					theirScore.setText(theirScore.getText()+" "+json_data.getInt("userScore"));
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			
		}
	}
	
	public JSONArray getScores(){
    	InputStream is = null;
    	String result = "";
    	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    	nameValuePairs.add(new BasicNameValuePair("gameId", gameId+""));
    	System.out.println("GameId: "+gameId);
    	
    	//http post
    	try{
    		HttpClient httpclient = new DefaultHttpClient();
    		HttpPost httppost = new HttpPost(KEY_121);
    		httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    		HttpResponse response = httpclient.execute(httppost);
    		HttpEntity entity = response.getEntity();
    		is = entity.getContent();
    	}catch(Exception e){
    		Log.e("log_tag", "Error in http connection: "+e);
    		return null;
    	}
    	
    	//convert response to string
    	try{
    		BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"),8);
    		StringBuilder sb = new StringBuilder();
    		String line = null;
    		while((line = reader.readLine()) != null){
    			sb.append(line + "\n");
    		}
    		is.close();
    		result = sb.toString();
    		System.out.println(result);
    	}catch(Exception e){
    		Log.e("log_tag", "Error converting result: "+e);
    		return null;
    	}
    	
    	//parse json data
    	JSONArray jArray = null;
    	try{
    		jArray = new JSONArray(result);
    		for(int i=0; i<jArray.length(); i++){
    			JSONObject json_data = jArray.getJSONObject(i);
    			Log.i("log_tag","userId: "+json_data.getInt("userId")+
    					", userScore: "+json_data.getString("userScore")
    			);
    		}
    	}catch(JSONException e){
    		Log.e("log_tag", "Error parsing data: "+e);
    		return null;
    	}
    	return jArray;
    }
}
